<template>
    <div class="order-list">
        <div class="order-tap-wrap">
            <order-tap :bannerProps="orderTap" @tapItem="tapOrderType" v-if="Object.keys(orderTap).length > 0"></order-tap>
        </div>
        <div class="order-list-wItem" v-for="(orderType,key) in orderTypes" v-if="orderType.id == nowShowItem" >
            <order-list-item
                    :orderProp="orderTypes[key]"
                    @refreshBuyBar="refreshBuyBar"
                    @getOrderList="getOrderList">
            </order-list-item>
        </div>
        <!--先关闭这里的支付-->
        <buy-bar :buyBarProp="buyBar"
                 v-if="nowShowItem == 0 && false"
                 @toPay="selectPayWay"></buy-bar>
        <!--支付方式选择的弹窗-->
        <slide-bottom v-if="payWayAlert" ref="payWay">
            <pay-way
                    :payWayProp="payWay"
                    @toPay="surePayWay"
                    @colsePayWay="colsePayWay"
            ></pay-way>
        </slide-bottom>
        <!--输入密码的弹窗-->
        <div class="input-password-wrap">
            <slide-bottom v-if="inputPassword" ref="inputPassword">
                <input-password
                        ref="inputPasswordAlert"
                        @closeInputPassword="closeInputPassword"
                        @submitPassword="toPay"></input-password>
            </slide-bottom>
        </div>
    </div>
</template>

<script>
    import MD5 from "js-md5";
    import XPay from '../../x/XPay'
    export default {
        name: "OrderList",
        data() {
            return {
                orderTap: {},
                payWay:{},//支付方式选择需要的参数
                payWayAlert:false,
                inputPassword:false,
                orderTypes:[
                    // {
                    //     order: {
                    //         id:0,
                    //         totalCount:0,
                    //         totalPages:0,
                    //         curPage:0,
                    //         "noSelectBtn": false,      //-------是否需要选中圆圈
                    //         list: [{
                    //             "selected": false,
                    //             "orderNum": "TR_19040384382004pp",      //-------订单号
                    //             "storeId": 527,         //---------店铺ID
                    //             "storeName": "木木木欧诺",     //-----------店铺名字
                    //             "storeLogo": "http://asd/190b4a495f5fff.jpg",     //----------店铺logo
                    //             "orderState": 1,       //-----订单的状态, 0:未付款, 1:已付订金（待通知提货|待发货）,2:待提货 | 待收货,3:交易完成  4:退款待卖家同意 5：退款待打款 6:退款完成 -1:交易关闭(拍卖单超时未支付) -2：订单失效（超时） -3：买家取消（未付款订单）
                    //             "stateDesc": "等待通知提货",          //----------订单状态描述
                    //             "deliveryType": 0,                   //----------订单配送类型  0, 到店提货  1, 同城快递
                    //             "waitingActResult": false,          //----------是否等待活动结果
                    //             "remainPayMs": 0,               //-------------剩余支付毫秒数
                    //             "orderAmount": "8872.4",        //-------------订单总额
                    //             "depositAmount": "8872.4",      //-------------保证金总额
                    //             "expressFreight": "8872.4",     //-------------运费
                    //             "userPayAmount": "887",         //-------------用户已付金额
                    //             "lastAmount": "7985.4",         //--------订单尾款（自提、待提货 且尾款为0，显示我要提货，点击展示提货码）
                    //             "deliveryQrCode": "order@delivery@code@TR@123@345",      //---------订单提货码（自提订单且待提货状态才有效）
                    //             "orderItemModels": [            //-------------订单商品列表
                    //                 {
                    //                     "itemId": 1787,         //------------商品ID
                    //                     "itemPhoto": "item/20175_offline/113685234100.png",     //---------商品图片
                    //                     "itemName": "哈哈，这个好",       //---------商品名称
                    //                     "styleName": "",        //--------购买款式
                    //                     "buyNum": 1,        //-------商品购买数量
                    //                     "itemPrice": "8872.4"       //----------商品售价
                    //                 }
                    //             ],
                    //             "orderOperateItems": [          //----------订单操作按钮项
                    //                 {
                    //                     "type": 0,          //------操作项类型：0-功能按钮 1-下拉按钮  2-纯文字
                    //                     "tag": "delete_order",      //------操作项标识
                    //                     "desc": "删除订单",     //-------文字描述
                    //                     "sonItems": null        //-------子项目列表(下拉按钮有效)
                    //                 },
                    //             ]
                    //         }]
                    //     },
                    // }
                ],
                buyBar:{
                },
                nowShowItem:0,
            }
        },
        mounted() {
            this.initOrderTap();
            this.initBuyBar();
            // this.$store.commit('orderList',{state:1});
        },
        methods: {
            initBuyBar(){
                /*TODO 待写*/
                let tempObj = {
                    noSelectBtn:true,//是否不需要选择的按钮
                    selectAll:false,//是否全选
                    totalMoney:0,//总金额
                    payMoney:{
                        money:0,
                        text:'合计'
                    },//商品总金额
                    btnText:'合并支付',
                    deposit:{//尾款
                        isShow:false,
                        money:0,
                    },
                    shippingFee:{
                        isShow:false,
                        money:0,
                    },//邮费、配送费用
                    warnText:'',//提示信息 温馨提示：某某商品为定制商品，暂不支持退款！
                };
                this.buyBar = Object.assign({},this.buyBar,tempObj)
            },
            refreshBuyBar(tempObj){
                this.buyBar = Object.assign({},this.buyBar,tempObj)
                console.log(this.buyBar);
            },
            initOrderTap() {
                let that = this;
                // let url= `${this.NW_API_API_LOCALE_VERSION}/order/list`;
                // this.xurl.get(url).then((data)=>{
                // });
                let url = `${this.NW_API_API_LOCALE_VERSION}/order/user/${this.userId}/statistic`;
                // "result": {
                //     "unPaidNum": 5,         -------待付款订单数量
                //     "deliveryNum": 115,         -------待取货订单数量
                //     "afterSaleNum": 15,     -------待售后订单数量
                //     "waitEvaluated": 23     --------待评价订单数量
                // }
                this.xurl.get(url).then(data => {
                    if (data.success) {
                        let list = [];
                        this.orderTap = Object.assign({}, this.orderTap, {
                            showNum: true,
                            showType: 'point',
                            list: [
                                {
                                    id: 0,//0-待付款 1-待收货 2-待售后 3-已完成
                                    name: '待付款',
                                    default: true,
                                    num:data.result.unPaidNum || 0,
                                },
                                {
                                    id: 1,
                                    name: '待取货',
                                    default: false,
                                    num:data.result.deliveryNum || 0,
                                },
                                {
                                    id: 2,
                                    name: '待售后',
                                    default: false,
                                    num:data.result.afterSaleNum || 0,
                                },
                                {
                                    id: 4,
                                    name: '待评价',
                                    default: false,
                                    num:data.result.waitEvaluated || 0,
                                },
                                {
                                    id: 3,
                                    name: '已完成',
                                    default: false,
                                    num:0,
                                }
                            ]
                        });
                        this.getOrderList({id:0,curPage:1});
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        this.$root.$emit('toast', {msg: '获取订单信息失败'});
                    }
                })
            },
            tapOrderType(obj) {
                let pageNum = 1;
                this.nowShowItem = obj.id;
                if(this.nowShowItem == 0){
                    this.totalPay();
                }
                this.getOrderList( {id:obj.id,curPage:pageNum} );
            },
            totalPay(){
                /*TODO 这里需要给一个合并支付的按钮*/
                // this.order
            },
            /*获取订单列表*/
            getOrderList( obj, isFresh=false ) {
                let that = this;
                let url = `${this.NW_API_API_LOCALE_VERSION}/order/list`;
                if(!isFresh && obj.curPage && obj.curPage > obj.totalPages){
                    return;
                }
                let parmas = {
                    "userId": this.userId,      //-----------用户ID
                    "orderMenu": obj.id,      //-----------订单菜单：0-待付款 1-待收货 2-待售后 3-已完成
                    "keyword": "",       //-----------关键字搜索
                    "pageNum": obj.curPage,        //-----------页码
                    "pageSize": 10,       //-----------每页个数
                }
                this.xurl.postDataJsonLoading(url, parmas).then(data => {
                    if (data.success) {
                        let tempObj = {};
                        if(this.orderTypes.length == 0 ){
                            this.orderTap.list.forEach((value,index)=>{
                                if(value.default){
                                    tempObj.id = obj.id;
                                }
                            })
                            tempObj = {
                                totalCount : data.totalCount,
                                totalPages : data.totalPages,
                                curPage : data.curPage,
                                list:data.list,
                                id : obj.id,
                            };
                            that.orderTypes.push(tempObj);
                        }else{
                            /*当前数据是否已经添加至this.orderTypes*/
                            let existId = false;
                            this.orderTypes.forEach((value,index)=>{
                                // console.log(value.id == obj.id)
                                /*是否为当前显示列表，是否为刷新，还是加载*/
                                if(value.id == obj.id){
                                    if( isFresh ){
                                        that.orderTypes[index] = Object.assign({},that.orderTypes[index],data);
                                        that.orderTypes.splice(index,1,that.orderTypes[index]);
                                        console.log(that.orderTypes[index]);
                                    }else{
                                        if( Array.isArray(that.orderTypes[index].list) && that.orderTypes[index].list.length > 0){
                                            that.orderTypes[index].list.push(...data.list);
                                        }
                                    }
                                    existId = true;
                                }
                            })
                            /*orderTypes中没有数据*/
                            if(!existId){
                                tempObj = {
                                    totalCount : data.totalCount,
                                    totalPages : data.totalPages,
                                    curPage : data.curPage,
                                    list:data.list,
                                    id : obj.id,
                                };
                                that.orderTypes.push(tempObj);
                            }
                        }
                        // this.order = Object.assign({},this.order,data);
                        // this.orderList =
                    } else if (data.errMsg) {
                        this.$root.$emit('toast', {msg: data.errMsg});
                    } else {
                        this.$root.$emit('toast', {msg: '获取订单信息失败'});
                    }
                })
            },
            /*选择支付方式*/
            selectPayWay(){
                /*TODO 这里要显示弹出框，选择支付方式*/
                let url = `${this.NW_API_API_LOCALE_VERSION}/capital/user/${this.userId}/get`;
                this.xurl.getLoading(url).then((data)=>{
                    this.payWay.accountMoney = data.result.cashAmount;
                    this.payWay.payMoney = this.buyBar.payMoney.money;
                    this.payWayAlert = true;
                    setTimeout(()=>{
                        if(this.$refs.payWay && this.$refs.payWay.showSlideBottom){
                            this.$refs.payWay.showSlideBottom();
                        }
                    },150)
                });
            },
            surePayWay(payWay){
                if(payWay == 'ACCOUNT'){
                    this.inputPassword = true;
                    this.payWayAlert = false;
                }else{
                    this.toPay(payWay);
                }
            },
            colsePayWay(){
                this.$refs.payWay.clickBord();
            },
            closeInputPassword(){
                this.payWayAlert = true;
                this.inputPassword = false;
                // this.$refs.inputPassword.clickBord();
            },
            toPay(payWay,password){
                let that = this;
                let passwordMd5 = ''
                if(password){
                    passwordMd5 = MD5(password);//支付密码
                }
                let url = '';//请求地址
                let payListArr = [];
                payWay = payWay || XPay.getPayChannel();
                that.orderTypes.forEach((cartStoreInfoValue,cartStoreInfoIndex)=>{
                    cartStoreInfoValue.list.forEach((cartItemInfoValue,cartItemInfoIndex)=>{
                        if( cartItemInfoValue.selected && cartItemInfoValue.orderState == 0){
                            payListArr.push(cartItemInfoValue.orderNum);
                        }
                    });
                })

                let params = {
                    "userId": that.userId,      //-----------------买家用户ID
                    "orderNums":payListArr      //----支付的订单列表
                };
                switch (payWay) {
                    case 'ACCOUNT'://账户支付
                        params = Object.assign({},params,{"payPwd": passwordMd5});
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/order/deposit`;
                        break;
                    case 'WECHAT'://微信支付
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/deposit `;
                        break;
                    case 'ALIPAY'://支付宝支付
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/deposit `;
                        break;
                    default :
                        url = `${this.NW_API_API_LOCALE_VERSION}/${payWay}/h5/prepay/deposit `;
                        break;
                }
                this.xurl.postDataJsonLoading(url,params).then((data) => {
                    if (data.success) {
                        /*这里跳转的页面还没有*/
                        if(payWay == "ACCOUNT"){
                            this.accountPaySuccess(data);
                        }else if(payWay == "WECHAT"){
                            this.payForWechat(data);
                        }else if(payWay == "ALIPAY"){
                            this.payForAlipay(data);
                        }
                    }else if(data.errMsg){
                        if(this.$refs.inputPasswordAlert){
                            this.$refs.inputPasswordAlert.passwordWrong = true;
                        }
                        that.$root.$emit('toast', {msg: data.errMsg});
                    }else{
                        that.$root.$emit('toast', {msg: '支付失败'});
                    }
                })
            },
            accountPaySuccess(data){
                if(this.$refs.payWay){
                    this.payWayAlert = false;
                }else if(this.$refs.inputPassword){
                    this.inputPassword = false;
                }
                this.$router.push({path:'/order/list',query:{tabId:0}})
                this.$root.$emit('toast', {msg: '支付成功'});
            },
            payForWechat(data){
                if(data.result.href){
                    window.location.href = data.result.href;
                }
            },
            payForAlipay(data){
                XPay.toPay(data.result.prepay);
            },
        },
        components: {
            'order-tap': () => import('../../../src/components/commonComponents/tap/Banner'),
            'order-list-item': () => import('./components/OrderListItem'),
            'buy-bar': () => import('../../components/commonActModel/buyBar/goodsBuyBar'),
            'pay-way': () =>  import('./components/PayWay'),
            'input-password': () =>  import('./components/InputPassWord'),
            'slide-bottom': () => import('../../components/commonComponents/slideBottom/SlideBottom'),
        }
    }
</script>

<style scoped lang="scss">
    .order-list /deep/ {
        .card-tab {
            z-index: 2;
        }
    }
    .order-tap-wrap{
        position: fixed;
        width: 100%;
        left: 0;
        top: 0;
        background-color: #fff;
        height: .41rem;
        z-index: 1030;
        border-bottom: 1px solid #E1E1E1;
    }
    .order-list-wItem{
        padding: .5rem .15rem 0;
    }

</style>